from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)

# 配置SQLite数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.root_path, 'data', 'users.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

# 创建用户模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)

# 初始化数据库
with app.app_context():
    db.create_all()
    # 添加一些默认用户
    if not User.query.filter_by(username='admin').first():
        admin_user = User(username='admin', password='admin')
        db.session.add(admin_user)
        db.session.commit()
    if not User.query.filter_by(username='user1').first():
        user1 = User(username='user1', password='password1')
        db.session.add(user1)
        db.session.commit()

@app.route('/', methods=['GET', 'POST'])
def login():
    # 如果是POST请求，处理表单提交
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        # 从数据库中验证用户名和密码
        user = User.query.filter_by(username=username).first()
        if user and user.password == password:
            # 登录成功，重定向到欢迎页面
            return redirect(url_for('welcome', username=username))
        else:
            # 登录失败，显示错误信息
            error = '用户名或密码错误，请重试'
            return render_template('login.html', error=error)
    
    # 如果是GET请求，显示登录页面
    return render_template('login.html')

@app.route('/welcome/<username>')
def welcome(username):
    return render_template('welcome.html', username=username)

if __name__ == '__main__':
    app.run(debug=True)